package com.kfgj.hkp.common.context;

import com.kfgj.hkp.common.auth.Token;
import com.kfgj.hkp.common.dic.Dictionary;
import com.kfgj.hkp.common.user.entity.BaseUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.NamedThreadLocal;

/**
 * Created by liwensihan on 2015-8-17.
 *
 * @author liwensihan
 */
public class CurrentContext {

    private static final ThreadLocal<RequestContext> requestContextThreadLocal =
            new NamedThreadLocal<RequestContext>("gn-request-context");

    public static void setRequestContext(RequestContext requestContext){
        requestContextThreadLocal.set(requestContext);
    }

    public static RequestContext getRequestContext(){
        RequestContext context = requestContextThreadLocal.get();
        if(context == null){
            context = new RequestContext();
            requestContextThreadLocal.set(context);
        }
        return requestContextThreadLocal.get();
    }

    public static void clean(){
        requestContextThreadLocal.remove();
    }


    public static BaseUserEntity getUserInfo() {
        if (requestContextThreadLocal.get()==null
                || StringUtils.isEmpty(requestContextThreadLocal.get().getUserCode())){
//            throw new BusinessException(ResponseMessage.UserNotLogin);
        }
        return requestContextThreadLocal.get()!=null?requestContextThreadLocal.get().getUserInfo():null;
    }

    public static Dictionary getDeviceType(){
        return requestContextThreadLocal.get().getClientType();
    }

    public static String getUserCode() {
        if (requestContextThreadLocal.get()==null
                || StringUtils.isEmpty(requestContextThreadLocal.get().getUserCode())){
//            throw new BusinessException(ResponseMessage.UserNotLogin);
        }
        return requestContextThreadLocal.get()!=null?requestContextThreadLocal.get().getUserCode():null;
    }

    public static String getCpyCode(){
        if(getUserInfo()!=null){
            return getUserInfo().getCpyCode();
        }

        return null;
    }

    public static String getAuthKey() {
        return requestContextThreadLocal.get()!=null?requestContextThreadLocal.get().getAuthKey():null;
    }

    public static String getSign() {
        return requestContextThreadLocal.get()!=null?requestContextThreadLocal.get().getSign():null;
    }


    public static String getRequestId() {
        return requestContextThreadLocal.get()!=null?requestContextThreadLocal.get().getRequestId(): null;
    }


    public static String getTimestamp() {
        return requestContextThreadLocal.get()!=null?requestContextThreadLocal.get().getTimestamp():null;

    }

    public static Token getToken(){
        return requestContextThreadLocal.get()!=null?requestContextThreadLocal.get().getToken():null;
    }

}
